package microcredit.gui.util;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dialog.ModalityType;
import java.awt.Frame;
import java.awt.HeadlessException;
import java.awt.Window;

import javax.swing.JComponent;
import javax.swing.JOptionPane;

import microcredit.gui.base.BaseDialog;

public class DialogUtilities {

	public static <E extends BaseDialog> E createModal(Component parent, String title,
			JComponent c, Class<E> baseClass) {
		Window w = getWindowForComponent(parent);
		ModalityType modalityType = ModalityType.DOCUMENT_MODAL;
		E dialog;
		try {
			dialog = baseClass.getConstructor(Window.class, ModalityType.class).newInstance(w, modalityType);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} 
		if (c != null) {
			dialog.getContentPane().add(c, BorderLayout.CENTER);
		}
		dialog.setTitle(title);
		dialog.pack();
		dialog.setLocationRelativeTo(getWindowForComponent(parent));
		return dialog;
	}

	public static Window getWindowForComponent(Component parentComponent)
			throws HeadlessException {
		if (parentComponent == null)
			return JOptionPane.getRootFrame();
		if (parentComponent instanceof Frame
				|| parentComponent instanceof Dialog)
			return (Window) parentComponent;
		return getWindowForComponent(parentComponent.getParent());
	}

	public static void showModal(Component parent, String title, JComponent c) {
		createModal(parent, title, c, BaseDialog.class).setVisible(true);
	}

}
